<?php
/**
 * Plugin for access permission validation. Called before Zend_Controller_Front enters its dispatch loop.
 * If user is permitted to access recource dispatching continue, if not user is redirected to login page. 
 * 
 * @author Konstantin Shamko <konstantin.shamko@gmail.com> 
 * @version 0.0.1
 * @copyright  Copyright (c) 2009 Konstantin Shamko
 * @category VaselinEngine
 * @package Bel Classes
 * @license  New BSD License
 *
 */
class Bel_Acl_Plugin extends Zend_Controller_Plugin_Abstract {
	
   /**
     * Called before Zend_Controller_Front enters its dispatch loop. Check if user has permission to access
     * module-controller-action
     *
     * @param  Zend_Controller_Request_Abstract $request
     * @return void
     */	
	public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request) {
		$acl = Zend_Registry::get ( 'acl' );
		$_groups = new Models_Usermanagement_Groups ( );
		$group = $_groups->getCurrentGroupId ();
		
		if (! $acl->has ( $request->getModuleName () . ':' . $request->getControllerName () . ':' . $request->getActionName () )) {
			return;
		}
		
		if (! $acl->isAllowed ( $group, $request->getModuleName () . ':' . $request->getControllerName () . ':' . $request->getActionName () )) {
			
			$this->_redirect ( $request, false );
		}
	}
	
	/**
	 * Sends user to login page (for not logged in users) or to special page for logged in users
	 *
	 * @param Zend_Controller_Request_Abstract $request
	 * @param bool $is_allowed
	 */
	private function _redirect($request, $is_allowed) {
		$auth = Models_Usermanagement_Auth::getInstance ();
		$module = $request->getModuleName ();
		
		if (! $is_allowed) {
			
			$seo =Bel_Seo::getInstance();
			$seo->setTitle(null); 
			
			if ($module == 'admin') {
				$request->setModuleName ( 'admin' );
			}else{
				$request->setModuleName ( 'usermanagement' );
			}				
			
			$request->setControllerName ( 'auth' );
			
			if ($auth->isLoggedIn ()) {			
				$request->setActionName ( 'forbidden' );
			} else {
				$request->setActionName ( 'loginform' );				
			}			
		}
	}
}